package com.rad.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.rad.dao.DBPool;
import com.rad.dao.ImageDaoITF;

public class ImageDaoImpl implements ImageDaoITF {

	@Override
	public void saveImageinfo(String imageTicket, String description) {
		if(imageTicket == null || "".equals(imageTicket)) {
			return;
		}
		Connection conn = null;
		PreparedStatement statement = null;
		ResultSet rs = null;
		try
		{
			//boolean imageTicketExists = false;
			boolean imageTicketExists = false;
			conn = DBPool.getConnection();
			statement = conn.prepareStatement(" select * from tab_imageinfo where filename = ? ");
			statement.setString(1, imageTicket);
			rs = statement.executeQuery();
			if(rs.next()){
				imageTicketExists = true;
			}
			DBPool.close(conn, statement, rs);
			
			conn = DBPool.getConnection();
			conn.setAutoCommit(false);
			String sql = "";
			if(imageTicketExists) {
				sql = "UPDATE tab_imageinfo SET description=? WHERE filename=?";
				statement = conn.prepareStatement(sql);
				statement.setString(1, description);
				statement.setString(2, imageTicket);
			}
			else {
				sql = "INSERT INTO tab_imageinfo VALUES (?, ?)";
				statement = conn.prepareStatement(sql);
				statement.setString(1, imageTicket);
				statement.setString(2, description);
			}
			statement.executeUpdate();
			conn.commit();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			DBPool.close(conn, statement, null);
		}
	}

	@Override
	public String getImageinfo(String imageTicket) {
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		String description = null;
		try
		{
			conn = DBPool.getConnection();
			pst = conn.prepareStatement(" select * from tab_imageinfo where filename = ? ");
			pst.setString(1, imageTicket);
			rs = pst.executeQuery();
			if(rs.next()){
				description = rs.getString("description");	
			}
			else {
				description = "";
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			DBPool.close(conn, pst, rs);
		}
		return description;
	}

}
